package com.chaos.meta.common;


import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;

public class CustomHandler extends AbstractColumnWidthStyleStrategy
{
	private static final int MAX_COLUMN_WIDTH = 255;
	//the maximum column width in Excel is 255 characters

	@Override
	protected void setColumnWidth(WriteSheetHolder writeSheetHolder, CellData cellData, Cell cell, Head head, int relativeRowIndex, boolean isHead) {

	}

	@Override
	public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, int relativeRowIndex, boolean isHead) {
		if (isHead && cell.getRowIndex() != 0) {
			int columnWidth = cell.getStringCellValue().getBytes().length;
			if (columnWidth > MAX_COLUMN_WIDTH) {
				columnWidth = MAX_COLUMN_WIDTH;
			} else {
				columnWidth = columnWidth + 3;
			}
			writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
		}

		//设置单元格格式为文本
		Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
		CellStyle cellStyle = workbook.createCellStyle();
		DataFormat dataFormat = workbook.createDataFormat();
		cellStyle.setDataFormat(dataFormat.getFormat("@"));
		cell.setCellStyle(cellStyle);
	}
}